package cn.wolfcode.car.controller;

import cn.wolfcode.car.domain.Permission;
import cn.wolfcode.car.domain.Role;
import cn.wolfcode.car.domain.RolePermission;
import cn.wolfcode.car.qo.RoleQueryObject;
import cn.wolfcode.car.service.IPermissionService;
import cn.wolfcode.car.service.IRolePermissionService;
import cn.wolfcode.car.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import result.JsonResult;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRolePermissionService rolePermissionService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    public String list(Model model, RoleQueryObject qo) {
        PageInfo<Role> list = roleService.list(qo);
        System.out.println(list);
        model.addAttribute("result", list);
        return "role/list";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() == null) {
            roleService.save(role);
        } else {
            roleService.update(role);
        }
        rolePermissionService.deleteByRoleId(role.getId());
        if (ids != null) {
            for (Long id : ids) {
                rolePermissionService.save(new RolePermission(role.getId(), id));
            }
        }
        return "redirect:/role/list";
    }

    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            Role role = roleService.get(id);
            model.addAttribute("role", role);
            List<Permission> permissions = permissionService.selectByRoleId(id);
            model.addAttribute("permissions", permissions);
        }
        List<Permission> permissionsAllList = permissionService.listAll();
        model.addAttribute("permissionsAllList", permissionsAllList);
        return "role/input";
    }


    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        roleService.delete(id);
        System.out.println(JsonResult.success(null));
        return JsonResult.success(null);
    }
}
